import { Global, Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { ConfigModule, ConfigService } from '@nestjs/config';
import path from 'path';
import { UsersEntity } from '../entities/user.entity';
import { EssayEntity } from '../entities/essay.entity';

/**
 * 加载配置文件
 */
import FileConfig from '../config/file';
import configuration from '../config/index';
// 引入使用
import * as dotenv from 'dotenv';
const envFilePath = `.env.${process.env.NODE_ENV || `development`}`;
import * as Joi from '@hapi/joi';
import { PassportModule } from '@nestjs/passport';
import { JwtModule } from '@nestjs/jwt';
import { jwtConstants } from '../passport/constants';
import { LocalStrategy } from '../passport/local.strategy';
import { JwtStrategy } from '../passport/jwt.strategy';


@Global()
@Module({
  imports: [
        //1.配置config目录
        ConfigModule.forRoot({
          cache: true,
          envFilePath,
          load: [
            () =>
              dotenv.config({
                path: '.env',
              }),
            configuration,
            FileConfig,
          ],
          ignoreEnvFile: false,
          //忽略配置文件，为true则仅读取操作系统环境变量，常用于生产环境
          isGlobal: true,
          //配置为全局可见，否则需要在每个模块中单独导入ConfigModule
          validationSchema: Joi.object({
            ENV: Joi.string()
              .valid('development', 'production', 'test', 'provision')
              .default('development'),
          }),
        }),
        //2.读取配置，这里读取的是数据库配置
        TypeOrmModule.forRootAsync({
          imports: [ConfigModule],
          inject: [ConfigService],
          useFactory: (config: ConfigService) => {
            console.log(config.get('db.mysql'));
            return {
              entities: [path.resolve(__dirname, '../**/**.entity{.ts,.js}')],
              ...config.get('db.mysql'),
            };
          },
        }),
        PassportModule.register({ defaultStrategy: 'local' }),
        JwtModule.register({
          secret: jwtConstants.secret,
          signOptions: { expiresIn: '24h' },
        }),
        TypeOrmModule.forFeature([UsersEntity, EssayEntity]),
  ],
  controllers: [],
  providers: [LocalStrategy, JwtStrategy],
  exports: [],
})
export class CommonModule {}
